
/**
 * 多SQL优化的工具类JS
 * 
 * 主要提供优化的一些工具方法
 */

var tunningBaseUrl = '/tunning/';

/**
* CloudDBA Error Code Define
*/
var AFFAIR_RIGHT = "0000";
var RIGHT_NO_ADVICE = "0008";

/**
 * Keys is used to update user click action 
 * Which should keep up with TunningKeys.java keys
 */
var CLICK_TUNNING_RESULT = 1;
var CLICK_FEEDBACK_STATE = 2;


//Common function util begin iframe page
var htmlDecode = function(data) {
	return Ext.util.Format.htmlDecode(data)
};

var showMessage = function(message, fn) {
	Ext.Msg.alert('提示' , message, fn);
}

var maskBody = function(message) {
	Ext.getCmp("tunningAdviceWindow").getEl().mask(message);
}

var unMaskBody = function() {
	Ext.getCmp("tunningAdviceWindow").getEl().unmask();
}

var closeWindow = function() {
	/**
	 * Note:
	 * 	下面的代码如果在Ext.getCmp("tunningAdviceWindow")'close事件中调用会出现死循环!!
	 */
//	Ext.getCmp("tunningAdviceWindow").close();
}

var handleAdviceResult = function(data) {
	var indexAdvices = data.indexAdvice;
	var jsonAdvices = JSON.parse(Ext.util.Format.htmlDecode(indexAdvices));
	return jsonAdvices.adviceList;
};
//Common function end 



Ext.define('TunningTaskDetail', {
	extend: 'Ext.data.Model',
	fields: [
	         {name: 'messageID', type:'string'},
	         {name: 'orginSQL', type: 'string'},
	         {name: 'formatSQL',  type: 'string'},
	         {name: 'gmtCreated',  type: 'string'},
	         {name: 'gmtModified',  type: 'string'},
	         {name: 'errorCode',  type: 'string'},
	         {name: 'errorMessage', type: 'string'},
	         {name: 'indexAdvice',  type: 'string'},
	         {name: 'tunningAdvice',type: 'string'},
	         {name: 'feedbackTunningGrade', type: 'string'},
	         {name: 'feedbackState', type:'string'},
	         {name: 'feedbackEditState', type:'string'},
	         {name: 'userFeedback', type:'string'},
	         {name: 'dmsFeedback', type:'string'}
	]
});




/**
 * When click "诊断结果" or "反馈状态"
 * Call this method
 */
var showSelectedTunningResult = function(option) {
	var selectedRecord = tunningPanel.tunningDataPanel.getSelectionModel().getSelection()[0];
	tunningPanel.tunningResultData = selectedRecord.data;
	
	// record click event to database
	Ext.getBody().mask('正在获取诊断SQL列表');
	ajax({
		url:tunningBaseUrl + 'saveQueryTunningEvent.do',
		onlyUrl: true,
		params:{
			option:option,
			dbName:nowDBName,
			panelKey:getPaneKey(),
			messageID:selectedRecord.data.messageID
		},
		success:function(resp) {
			Ext.getBody().unmask();
			showTunningResult(selectedRecord.data);
		},
		failure:function(resp) {Ext.getBody().unmask();Ext.Msg.alert('提示' , resp.responseText);}
	});
	
};

//Show tunning Result begin

var showTunningResult = function(data) {
	
	/**
	 * Comment the code
	 * If data.errorCode == RIGHT_NO_ADVICE
	 * App server will add a '无诊断建议' in adviceList
	 */
//	if(data.errorCode == RIGHT_NO_ADVICE) {
//		Ext.Msg.alert('提示' , '无诊断建议');
//		return ;
//	}
	
	/**
	 * We must consider the following state
	 * RIGHT_NO_ADVICE, AFFAIR_RIGHT, TUNNING_NOW, ERROR_STATE 
	 * 
	 * AFFAIR_RIGHT is ignored
	 * RIGHT_NO_ADVICE is considered above
	 * TUNNING_NOW has no link and cannot come in this method
	 * SO we just need to consider ERROR_STATE
	 */
	if(data.errorCode != AFFAIR_RIGHT && data.errorCode != RIGHT_NO_ADVICE) {
		Ext.Msg.alert('提示' , data.errorMessage);
		return ;
	}
	
	if(data) {
		var adviceWindow = Ext.create('Ext.window.Window', {
  	    title: '诊断结果',
  	    height: 400,
  	    width: 720,
  	    modal:true,
  	    id:'tunningAdviceWindow',
  	    x:150,
  	    y:50,
  	    layout : 'fit',
  	    closable : true,
  	    buttonAlign:'center',
//  	    html:renderHtml(data),
  	    autoScroll:true,
  	    items : [{
  	        xtype : "component",
  	        border: false,
  	        autoEl : {
  	            tag : "iframe",
  	            // 这里每个数据库调用url都是一样的
  	            src : "/$dbType" + tunningBaseUrl +  "tunningResultPage.do?token=" + getUserToken()
  	        }
  	    }],
  	    listeners: {
  	    	 close:{
  	    		 fn:function( panel, eOpts ) {
  	    			 closeWindow();
  	    		 }
  	    	 }
  	    }
  	   
			/*,
  	    buttons:[{
  	    	text: '关闭', 
  	    	handler:function () {
  	    				adviceWindow.close();
              		}
  	    	}
  	    ]*/
  	    
  	});
		adviceWindow.show();
	} else {
		Ext.Msg.alert('提示' , '诊断结果数据异常，不能查看！');
	}
	
};

//Show tunning desc window
var showTunningDesc = function() {
    var textValue =
                '============================================================================\n' +
                '     SQL优化功能可以为您的慢SQL提供索引建议、检测因隐式转换，函数等表达式不能使用索引的情况。请大家参考以下几个例子：\n' +
                '============================================================================\n' +
                '\n      1.创建表：' +
                '\n         CREATE TABLE `tb1` (' +
                '\n         	`c1` int(11) NOT NULL,' +
                '\n         	`c2` varchar(32) DEFAULT NULL,' +
                '\n         	`c3` double DEFAULT NULL,' +
                '\n         	KEY `IDX_C2` (`c2`),' +
                '\n         	KEY `IDX_C3` (`c3`)' +
                '\n         ) ENGINE=InnoDB DEFAULT CHARSET=utf8' + '\n' +
                '\n      2.插入数据：' +  
                '\n         insert into `tb1`(`c1`,`c2`,`c3`) values' +
                "\n         	('1','a1',3.14159), ('2','a2',3.1321), ('3','a3', 3111), ('4','a4', 123), ('5','a5',3.1234), ('6','a6',3.1122), ('7','a7', 4321);" +
                '\n\n============================================================================\n' +
                '\n      例子1（生成索引建议）：' +
                '\n       SQL:  SELECT * FROM tb1 where c1 = 1;' +
                '\n       建议 ：     ALTER TABLE tb1 ADD INDEX IDX_C1 (C1)' +
                '\n       原因 ：     C1 = 1 能够筛选出一行数据，我们认为这个字段过滤性比较高，所以推荐在C1上创建索引。 ' +
                '\n\n============================================================================\n' +
                '\n      例子2（检测隐式转换）：' +
                '\n       SQL:  SELECT * FROM tb1 where c2 = 1;' +
                "\n       建议 ：     表达式【tb1.c2 = 1】存在隐式转换，会导致不能使用该列索引，建议使用【tb1.c2 = '1'】。" +
                '\n\n============================================================================\n' +
                '\n      例子3（检测函数）：' +
                '\n       SQL:  SELECT * FROM tb1 where ABS(c3) = 123;' +
                '\n       建议 ：     表达式【ABS(c3)】的索引列使用函数会导致不能使用该列索引,建议改写该表达式。'  +
                '\n\n\n\n';
    var win = new IDB.Window({
        width:800,height:500, x:150, y:20,autoScroll:true,maximizable:true,closable:true,title:'SQL优化功能描述',layout:'fit',
        items:[{
            xtype:'textarea',value:textValue
        }]
    });
};


//Show tunning desc window
var showMSSQLTunningDesc = function() {
    var textValue =
                '============================================================================\n' +
                '     SQL优化功能可以为您的慢SQL提供索引建议、检测因隐式转换，函数等表达式不能使用索引的情况。请大家参考以下几个例子：\n' +
                '============================================================================\n' +
                '\n      1.创建表：' +
                '\n         BEGIN TRANSACTION GO' +
                '\n         CREATE TABLE [dbo].[tb1](' +
                '\n         	[c1] int NOT NULL ,' +
                '\n         	[c2] varchar(50) NOT NULL ,' +
                '\n         	[c3] decimal(18,0) NOT NULL ' +
                '\n         ) ON [PRIMARY]; GO ' + '\n' +
                '\n         CREATE NONCLUSTERED INDEX [IX_tb1_c2] ON [dbo].[tb1] ([c2])  GO ' + '\n' +
                '\n         CREATE NONCLUSTERED INDEX [IX_tb1_c3] ON [dbo].[tb1] ([c3])  GO' + '\n' +
                '\n         ) ON [PRIMARY]; GO COMMIT; ' + '\n' +
                '\n      2.插入数据：' +  
                '\n         insert into  [dbo].[tb1] values(1, \'a1\', 11.11);' +
                "\n         insert into  [dmstest].[dbo].[tb1] values(2, 'a2', 22.22);" +
                '\n\n============================================================================\n' +
                '\n      例子1（生成索引建议）：' +
                '\n       SQL:  SELECT * FROM tb1 where c1 = 1;' +
                '\n       建议 ：     CREATE INDEX IDX_C1 ON tb1 (C1) WITH(ONLINE=ON)' +
                '\n       原因 ：     C1 = 1 能够筛选出一行数据，我们认为这个字段过滤性比较高，所以推荐在C1上创建索引。 ' +
                '\n\n============================================================================\n' +
                '\n      例子2（检测隐式转换）：' +
                '\n       SQL:  SELECT * FROM tb1 where c2 = 1;' +
                "\n       建议 ：     表达式【tb1.c2 = 1】存在隐式转换，会导致不能使用该列索引，建议使用【tb1.c2 = '1'】。" +
                '\n\n============================================================================\n' +
                '\n      例子3（检测函数）：' +
                '\n       SQL:  SELECT * FROM tb1 where ABS(c3) = 123;' +
                '\n       建议 ：     表达式【ABS(c3)】的索引列使用函数会导致不能使用该列索引,建议改写该表达式。'  +
                '\n\n\n\n';
    var win = new IDB.Window({
        width:800,height:500, x:150, y:20,autoScroll:true,maximizable:true,closable:true,title:'SQL优化功能描述',layout:'fit',
        items:[{
            xtype:'textarea',value:textValue
        }]
    });
};

